package Servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.DanhMucDAO;
import POJO.DanhMuc;
import POJO.NguoiDung;

/**
 * Servlet implementation class DanhMucSanPhamServlet
 */
//@WebServlet("/DanhMucSanPhamServlet")
public class DanhMucSanPhamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DanhMucSanPhamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//	     Trả về id mang thông tin cho trang chủ index.jsp
	    
	    //get session
	    HttpSession session = request.getSession();
        String err = (String) session.getAttribute("id");
        
        if(err == "1")
        {
        //da dang nhap
            
            NguoiDung nguoiDung = (NguoiDung) session.getAttribute("nguoiDung");
            if (nguoiDung.getLoai() == 2 || nguoiDung.getLoai() == 4)
            {
                request.setAttribute("id", "1");
                ArrayList<DanhMuc> list = DanhMucDAO.SelectDanhMucALL();
                
                request.setAttribute("listDanhMuc", list);
                
                RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
                dispatcher.forward(request, response);
            }
            else
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("/view/Permission.jsp");
                dispatcher.forward(request, response);
            }
        }
        else
        {
            //chua dang hap ---> login
            response.sendRedirect("login");
        }
	   
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    request.setAttribute("id", "1");

        String str = request.getParameter("timKiem");
        str = new String(str.getBytes("ISO-8859-1"), "UTF-8");

        ArrayList<DanhMuc> list = DanhMucDAO.SearchDanhMucByName(str);

        request.setAttribute("listDanhMuc", list);

        RequestDispatcher dispatcher = request
                .getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
	}

}
